import React, { useState } from 'react';
import { Space, Tag, Button, message, Modal, Tooltip, App as AntdApp } from 'antd';
import { UserOutlined, EditOutlined, DeleteOutlined, EyeOutlined, PlusOutlined, ExclamationCircleOutlined, TeamOutlined, MenuOutlined } from '@ant-design/icons';
import AdvancedTable from '@/components/common/AdvancedTable/AdvancedTable';
import { useTable } from '@/components/common/AdvancedTable/useTable';
import type { Role, RolePageParams, RoleCreateParams, RoleUpdateParams } from '@/api/system';
import { getRolePage, createRole, updateRole, deleteRole } from '@/api/system';
import { DynamicForm } from '@/components/common/DynamicForm';
import { createRoleFormConfig } from './components/RoleFormConfig';
import UserAssignDialog from './components/UserAssignDialog';
import MenuAssignDialog from './components/MenuAssignDialog';

const Roles: React.FC = () => {
  const { modal } = AntdApp.useApp();
  const [roleFormVisible, setRoleFormVisible] = useState(false);
  const [editingRole, setEditingRole] = useState<Role | null>(null);
  const [viewingRole, setViewingRole] = useState<Role | null>(null);
  const [stickyHeaderEnabled, setStickyHeaderEnabled] = useState(true);
  const [assignDialogVisible, setAssignDialogVisible] = useState(false);
  const [assigningRole, setAssigningRole] = useState<Role | null>(null);
  const [menuAssignDialogVisible, setMenuAssignDialogVisible] = useState(false);
  const [menuAssigningRole, setMenuAssigningRole] = useState<Role | null>(null);

  // 表格配置
  const table = useTable<Role>({
    queryKey: 'system-roles',
    fetchData: async (params) => {
      const response = await getRolePage({
        pageNo: params.page,
        pageSize: params.pageSize,
        code: params.search?.code,
        name: params.search?.name,
      });

      // API 响应处理
      if (!response) {
        return {
          data: [],
          total: 0,
          page: params.page,
          pageSize: params.pageSize,
        };
      }

      // 根据新的API响应结构处理数据
      return {
        data: Array.isArray(response.list) ? response.list : [],
        total: parseInt(response.total) || 0,
        page: params.page,
        pageSize: params.pageSize,
      };
    },
    defaultPageSize: 10,
    searchFields: [
      {
        key: 'code',
        label: '角色编码',
        type: 'input',
        placeholder: '请输入角色编码',
      },
      {
        key: 'name',
        label: '角色名称',
        type: 'input',
        placeholder: '请输入角色名称',
      },
    ],
    onSuccess: (data) => {
      // 角色数据获取成功
    },
    onError: (error) => {
      // 角色数据获取失败
      message.error('角色数据加载失败');
    },
  });

  // 表格列定义
  const columns = [
    {
      key: 'id',
      title: 'ID',
      dataIndex: 'id',
      width: 80,
      sorter: true,
      hidden: true, // 隐藏ID列
    },
    {
      key: 'code',
      title: '角色编码',
      dataIndex: 'code',
      width: 150,
      sorter: true,
      render: (text: string) => (
        <Space>
          <UserOutlined />
          {text}
        </Space>
      ),
    },
    {
      key: 'name',
      title: '角色名称',
      dataIndex: 'name',
      width: 150,
      sorter: true,
      render: (text: string) => text || '-',
    },
    {
      key: 'createTime',
      title: '创建时间',
      dataIndex: 'createTime',
      width: 180,
      sorter: true,
      render: (text: string) => text ? new Date(text).toLocaleString() : '-',
    },
    {
      key: 'updateTime',
      title: '更新时间',
      dataIndex: 'updateTime',
      width: 180,
      sorter: true,
      render: (text: string) => text ? new Date(text).toLocaleString() : '-',
    },
    {
      key: 'actions',
      title: '操作',
      dataIndex: 'actions',
      width: 300,
      fixed: 'right',
      render: (_text: any, record: Role) => (
        <Space size="small">
          <Tooltip title="查看">
            <Button
              type="link"
              size="small"
              icon={<EyeOutlined />}
              onClick={() => handleViewRole(record)}
            />
          </Tooltip>
          <Tooltip title="编辑">
            <Button
              type="link"
              size="small"
              icon={<EditOutlined />}
              onClick={() => handleEditRole(record)}
            />
          </Tooltip>
          <Tooltip title="分配用户">
            <Button
              type="link"
              size="small"
              icon={<TeamOutlined />}
              onClick={() => handleAssignUsers(record)}
            />
          </Tooltip>
          <Tooltip title="分配菜单">
            <Button
              type="link"
              size="small"
              icon={<MenuOutlined />}
              onClick={() => handleAssignMenus(record)}
            />
          </Tooltip>
          <Tooltip title="删除">
            <Button
              type="link"
              size="small"
              danger
              icon={<DeleteOutlined />}
              onClick={() => handleDeleteRole(record)}
            />
          </Tooltip>
        </Space>
      ),
    },
  ];

  // 批量操作
  const batchActions = [
    {
      key: 'batchDelete',
      label: '批量删除',
      icon: <DeleteOutlined />,
      danger: true,
      onClick: (selectedRows: Role[]) => {
        modal.confirm({
          title: '确认批量删除',
          content: `确定要删除选中的 ${selectedRows.length} 个角色吗？`,
          icon: <ExclamationCircleOutlined />,
          onOk: async () => {
            try {
              await deleteRole(selectedRows.map(row => row.id));
              message.success(`成功删除 ${selectedRows.length} 个角色`);
              table.refresh();
            } catch (error) {
              message.error('批量删除失败');
            }
          },
        });
      },
    },
  ];

  // 查看角色
  const handleViewRole = (role: Role) => {
    setViewingRole(role);
  };

  // 编辑角色
  const handleEditRole = (role: Role) => {
    setEditingRole(role);
    setRoleFormVisible(true);
  };

  // 删除角色
  const handleDeleteRole = (role: Role) => {
    modal.confirm({
      title: '确认删除',
      content: `确定要删除角色 "${role.name}" 吗？`,
      icon: <ExclamationCircleOutlined />,
      onOk: async () => {
        try {
          await deleteRole(role.id);
          message.success('删除成功');
          table.refresh();
        } catch (error) {
          message.error('删除失败');
        }
      },
    });
  };

  // 创建角色
  const handleCreateRole = () => {
    setEditingRole(null);
    setRoleFormVisible(true);
  };

  // 分配用户
  const handleAssignUsers = (role: Role) => {
    setAssigningRole(role);
    setAssignDialogVisible(true);
  };

  // 分配菜单
  const handleAssignMenus = (role: Role) => {
    setMenuAssigningRole(role);
    setMenuAssignDialogVisible(true);
  };

  // 处理表单提交
  const handleFormSubmit = async (values: RoleCreateParams | RoleUpdateParams) => {
    try {
      if (editingRole) {
        // 更新角色
        await updateRole(values as RoleUpdateParams);
        message.success('角色更新成功');
      } else {
        // 创建角色
        await createRole(values as RoleCreateParams);
        message.success('角色创建成功');
      }
      setRoleFormVisible(false);
      table.refresh();
    } catch (error) {
      message.error(editingRole ? '角色更新失败' : '角色创建失败');
    }
  };

  // 生成动态表单配置
  const roleFormConfig = createRoleFormConfig(!!editingRole);

  return (
    <div style={{ padding: 24, height: 'calc(100vh - 180px)', display: 'flex', flexDirection: 'column' }}>
      <AdvancedTable<Role>
        columns={columns}
        dataSource={table.data}
        loading={table.loading}
        pagination={table.pagination}
        searchFields={table.searchFields}
        onSearch={table.handleSearch}
        refresh={table.refresh}
        batchActions={batchActions}
        stickySettings={{
          enabled: true,
          header: stickyHeaderEnabled,
          offsetTop: 64,
          onHeaderChange: (enabled) => {
            setStickyHeaderEnabled(enabled);
          },
        }}
        scroll={{ x: 1000 }}
        extra={
          <Button type="primary" icon={<PlusOutlined />} onClick={handleCreateRole}>
            新增角色
          </Button>
        }
        onChange={table.handleTableChange}
        rowSelection={{
          type: 'checkbox',
          onChange: (selectedRowKeys, selectedRows) => {
            // 行选择变化处理
          },
        }}
        rowClassName={(_record, index) => {
          return index % 2 === 0 ? 'even-row' : 'odd-row';
        }}
        onRow={(record) => {
          return {
            onClick: (_event) => {
              // 行点击处理
            },
            onDoubleClick: (_event) => {
              // 行双击处理
            },
          };
        }}
      />

      {/* 角色表单对话框 */}
      <DynamicForm
        config={roleFormConfig}
        values={editingRole || undefined}
        visible={roleFormVisible}
        onSubmit={handleFormSubmit}
        onCancel={() => setRoleFormVisible(false)}
        width={600}
      />

      {/* 角色详情对话框 */}
      <Modal
        title="角色详情"
        open={!!viewingRole}
        onCancel={() => setViewingRole(null)}
        footer={null}
        width={600}
      >
        {viewingRole && (
          <div style={{ padding: '20px 0' }}>
            <Space direction="vertical" style={{ width: '100%' }} size="middle">
              <div>
                <strong>角色编码：</strong>
                <span style={{ marginLeft: 8 }}>{viewingRole.code}</span>
              </div>
              <div>
                <strong>角色名称：</strong>
                <span style={{ marginLeft: 8 }}>{viewingRole.name}</span>
              </div>
              <div>
                <strong>创建时间：</strong>
                <span style={{ marginLeft: 8 }}>
                  {viewingRole.createTime ? new Date(viewingRole.createTime).toLocaleString() : '-'}
                </span>
              </div>
              <div>
                <strong>更新时间：</strong>
                <span style={{ marginLeft: 8 }}>
                  {viewingRole.updateTime ? new Date(viewingRole.updateTime).toLocaleString() : '-'}
                </span>
              </div>
            </Space>
          </div>
        )}
      </Modal>

      {/* 用户分配对话框 */}
      {assigningRole && (
        <UserAssignDialog
          visible={assignDialogVisible}
          roleId={assigningRole.id}
          roleName={assigningRole.name}
          onClose={() => {
            setAssignDialogVisible(false);
            setAssigningRole(null);
          }}
          onSuccess={() => {
            table.refresh();
          }}
        />
      )}

      {/* 菜单分配对话框 */}
      {menuAssigningRole && (
        <MenuAssignDialog
          visible={menuAssignDialogVisible}
          roleId={menuAssigningRole.id}
          roleName={menuAssigningRole.name}
          onClose={() => {
            setMenuAssignDialogVisible(false);
            setMenuAssigningRole(null);
          }}
          onSuccess={() => {
            table.refresh();
          }}
        />
      )}
    </div>
  );
};

export default Roles;